package org.ucas.kgraph.controller;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.ucas.kgraph.dto.AccountDto;
import org.ucas.kgraph.dto.CarryDto;
import org.ucas.kgraph.dto.DocumentDto;
import org.ucas.kgraph.dto.ErrDto;
import org.ucas.kgraph.dto.ListDto;
import org.ucas.kgraph.dto.UploadDto;
import org.ucas.kgraph.dto.ResponseDto;
import org.ucas.kgraph.dto.RoleDto;
import org.ucas.kgraph.dto.TermDto;
import org.ucas.kgraph.entity.Account;
import org.ucas.kgraph.entity.DocFile;
import org.ucas.kgraph.entity.Document;
import org.ucas.kgraph.entity.Term;
import org.ucas.kgraph.entity.UserProfile;
import org.ucas.kgraph.service.DocFileService;
import org.ucas.kgraph.service.DocumentService;
import org.ucas.kgraph.service.SchemService;
import org.ucas.kgraph.service.TermService;
import org.ucas.kgraph.service.UserService;
import org.ucas.kgraph.utils.common.DigestUtil;
import org.ucas.kgraph.utils.common.EncodeUtil;
import org.ucas.kgraph.utils.exception.ForbiddenException;
import org.ucas.kgraph.utils.exception.NotFoundException;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Optional;
import java.util.UUID;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Controller
@ResponseBody
public class DocumentController extends BaseController{

  @Autowired
  private DocumentService documentService;
  @Autowired
  private DocFileService docFileService;

  @RequestMapping(value = "/document/image",method = RequestMethod.POST)
  public CarryDto<UploadDto> uploadImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
	  UploadDto dto=new UploadDto();
	  CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
	  if(multipartResolver.isMultipart(request))
      {
		
          MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
          MultipartFile file = multiRequest.getFile(multiRequest.getFileNames().next());
         
            String realPath = request.getSession().getServletContext().getRealPath("/")+"/WEB-INF/classes/static/upload/";
          	
            File realPathDirectory = new File(realPath);
            if (realPathDirectory == null || !realPathDirectory.exists()) {
                realPathDirectory.mkdirs();
            }
            String fileName = null;
              if(file!=null)
              {
            	  UUID uuid = UUID.randomUUID();
            	  String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
            	  SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
            	  //System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
                  fileName ="pic_" + (df.format(new Date()))+uuid.toString()+suffix;
                  dto.setSrc("/upload/"+fileName);
                  File uploadFile = new File(realPathDirectory.getPath() + "/" + fileName);
                  //System.out.println("==============================================="+uploadFile.getPath());
                  file.transferTo(uploadFile);
                  return CarryDto.of(dto);
              }
    }
	return CarryDto.of(dto);
  }
  @RequestMapping(value = "/document/upload/doc/{id:\\d+}",method = RequestMethod.POST)
  public CarryDto<UploadDto> upLoadDoc(@PathVariable Long id,HttpServletRequest request,HttpServletResponse response) throws IOException{
	  UploadDto dto=new UploadDto();
	  CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
	  if(multipartResolver.isMultipart(request))
      {

          MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
          MultipartFile file = multiRequest.getFile(multiRequest.getFileNames().next());
          String realPath = request.getSession().getServletContext().getRealPath("/")+"/WEB-INF/classes/static/updoc/";
          File realPathDirectory = new File(realPath);
          if (realPathDirectory == null || !realPathDirectory.exists()) {
              realPathDirectory.mkdirs();
          }
          String fileName = null;
          if(file!=null)
          {
        	  UUID uuid = UUID.randomUUID();
              String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
              SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
              fileName =(df.format(new Date()))+uuid.toString()+suffix;
              File uploadFile = new File(realPathDirectory.getPath() + "/" + fileName);
             // File uploadFile = new File(realPathDirectory.getPath() + "/" + "test.pdf");
              DocFile docFile = new DocFile();
              docFile.setPath(uploadFile.getPath());
              String name = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
              docFile.setName(name+suffix);
              
              docFileService.save(docFile);
              documentService.addDocFile(id,docFile);
              dto.setSrc(name+suffix);
              dto.setId(docFile.getId());
              file.transferTo(uploadFile);
              return CarryDto.of(dto);
              
          }
    }
	return CarryDto.of(dto);
  }
  
  
  @RequestMapping(value = "/document/delete/doc",method = RequestMethod.GET)
  public ResponseDto deleteDoc(@RequestParam("documentid") Long documentId,@RequestParam("docid") Long docId){
	  documentService.deleteDocfile(documentId,docId);
	  return ResponseDto.OK;
  }
  
  
  @ResponseBody  
  @RequestMapping(value = "/document/download/doc/{id:\\d+}",method = RequestMethod.GET)  
  public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response)  
        throws IOException {
	DocFile docFile = docFileService.findById(id);
	String filepath = docFile.getPath();
	//filepath=request.getSession().getServletContext().getRealPath("/")+"/WEB-INF/classes/static/updoc/test.pdf";
	int beginIndex = filepath.lastIndexOf(File.separator);  
	int endIndex = filepath.lastIndexOf(".");  
	String filename = docFile.getName();
	try {  
    	filename = URLEncoder.encode(filename, "UTF-8");  
    } catch (UnsupportedEncodingException e1) {  
        e1.printStackTrace();  
    }
	response.setHeader("Content-Disposition", "attachment;filename="  
			                + filename);  
			  
    BufferedInputStream bis = null;  
    FileInputStream fis = null;  
    BufferedOutputStream bos = null;  
  
    try {  
        fis = new FileInputStream(filepath);  
        bis = new BufferedInputStream(fis);  
  
        int length = bis.available();  
        response.setContentLength(length);  
  
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] data = new byte[1024];  
        while (bis.read(data) != -1) {  
            bos.write(data);  
            bos.flush();  
        }  
    } catch (FileNotFoundException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        try {  
            fis.close();  
            bis.close();
        } catch (IOException e) {}  
    }
 }  

  

  
  
  @RequestMapping(value = "/documents",method = RequestMethod.POST)
  public CarryDto<DocumentDto> create( HttpServletRequest request){
    Long parentId =  request.getParameter("parent")==null?null:Long.valueOf(request.getParameter("parent"));
    DocumentDto dto = new DocumentDto();
    Document tmp = new Document();
    if(parentId==null) documentService.create(tmp);
    //else documentService.createWithParent(tmp,parentId);
    //relationService.create(new Relation(tmp.getId(),parentId, RelationType.Parent));
    dto.id = tmp.getId();
    return CarryDto.of(dto);
  }
  
  @RequestMapping(value = "/documents/{id:\\d+}/copy",method = RequestMethod.POST)
  public CarryDto<DocumentDto> copy(@PathVariable Long id, HttpServletRequest request){
    Long parentId =  request.getParameter("parent")==null?null:Long.valueOf(request.getParameter("parent"));
    DocumentDto dto = new DocumentDto();
    Document tmp = new Document();
    if(parentId==null) documentService.create(tmp);
    Document fromtmp=documentService.load(id);
    //else documentService.createWithParent(tmp,parentId);
    //relationService.create(new Relation(tmp.getId(),parentId, RelationType.Parent));
    
    tmp = documentService.recontent(tmp.getId(),fromtmp);
    dto.id = tmp.getId();
    return CarryDto.of(dto);
  }
  
  
  @RequestMapping(value = "/documents/{id:\\d+}/recontent",method = RequestMethod.PUT)
  public CarryDto<DocumentDto> recontent(@PathVariable Long id,@RequestParam("content") String content){
    Document tmp = documentService.recontent(id,content);
    return CarryDto.of(DocumentDto.of(tmp));
  }
  
  
  @RequestMapping(value = "/documents/{id:\\d+}",method = RequestMethod.GET)
  public CarryDto<DocumentDto> load(@PathVariable Long id){
    Document doc = documentService.load(id);
    if(doc == null) throw NotFoundException.Term_NotExists;
    else return CarryDto.of(DocumentDto.of(doc));
  }
}
